<template>
  <div class="reportEditOrAdd" style="height： 100vh;">
    <div class="crumbs-box">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/content/list?tabsName=Report' }">内容管理</el-breadcrumb-item>
        <el-breadcrumb-item v-if="$route.query && $route.query.param">编辑教研报告</el-breadcrumb-item>
        <el-breadcrumb-item v-else>添加教研报告</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content-box">
      <div class="report-title">上传教研报告</div>

      <div class="teaching-box">
        <div class="title">基本信息</div>
        <el-form
          v-if="ruleForm"
          ref="ruleForm"
          :rules="rules"
          class="teaching-form"
          label-width="140px"
          :model="ruleForm"
        >
          <el-form-item label="报告标题：">
            <el-col :span="12">
              <el-input v-model="ruleForm.title" placeholder="请输入标题，如小蝌蚪找妈妈" />
            </el-col>
          </el-form-item>

          <!-- <el-form-item label="选中教研活动：">
            <el-col :span="12">
              <el-select v-model="ruleForm.region" style="width: 100%;" placeholder="请选择教研活动">
                <el-option label="区域一" value="shanghai" />
                <el-option label="区域二" value="beijing" />
              </el-select>
            </el-col>
          </el-form-item>-->

          <el-form-item v-if="options.cateTags" label="教研报告分类：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.cateTagsSelect"
                style="width: 100%;"
                :options="options.cateTags"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                placeholder="请选择/输入，每个点用逗号隔开"
                clearable
                filterable
                @keyup.enter.native="tabsKeyup($event, 1)"
              />
            </el-col>
          </el-form-item>

          <el-form-item v-if="options.colTags" label="教研报告标签：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.colTagsSelect"
                style="width: 100%;"
                :options="options.colTags"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                placeholder="请选择/输入，每个点用逗号隔开"
                clearable
                filterable
                @keyup.enter.native="tabsKeyup($event, 1)"
              />
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div v-if="ruleForm" class="teaching-box">
        <div class="title">文件</div>
        <el-form ref="ruleForm" class="teaching-form" label-width="140px" :model="ruleForm">
          <el-form-item>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="true"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="ruleForm.fileList"
              >
                <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.ppt .xls .doc .docx .pdf .jpg...</div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="teaching-box">
        <div class="title">教研介绍</div>
        <el-form
          v-if="ruleForm"
          ref="ruleForm"
          class="teaching-form"
          label-width="140px"
          :model="ruleForm"
        >
          <el-form-item>
            <el-col :span="22">
              <editor v-model="ruleForm.textContent" @input="newContent" />
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="button-box">
        <button class="submit" @click="onSubmit('ruleForm')">发布</button>
      </div>
    </div>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads';
import { getTeachingResearchReport, findColumnTags, findTagsList, updateReport } from '@/api/content';
import Tinymce from '@/components/Tinymce/index';
import { reduceArr, assignment, compose } from '@/utils/categoryOrTags';

export default {
  name: 'ReportEditOrAdd',
  components: {
    editor: Tinymce
  },
  data () {
    return {
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},

      options: {
        cateTags: '',
        colTags: ''
      },
      ruleForm: null,
      rules: {
        name: [
          { required: true, message: '请输入标题!', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择教研活动!', trigger: 'change' }
        ]
      },

      fileList: []
    };
  },
  created () {
    if (this.$route.query.param) {
      this.init();
    } else {
      this.$router.push({
        path: '/content/list',
        params: {
          tabsName: 'Report'
        }
      });
      return;
    }
  },
  methods: {
    newContent (val) {
      this.ruleForm.textContent = val;
    },
    async init () {
      this.loading = true;
      getTeachingResearchReport(this.$route.query.param)
        .then(res => {
          this.ruleForm = res.data;
          this.loading = true;
          if (this.ruleForm.teachingResearch.teachingTarget === '') {
            this.ruleForm.teachingResearch.teachingTarget = {
              cateId: '',
              itemName: '',
              itemCode: ''
            };
          }
          if (this.ruleForm.teachingResearch.phase === '') {
            this.ruleForm.teachingResearch.phase = {
              cateId: '',
              itemName: '',
              itemCode: ''
            };
          }
          if (this.ruleForm.teachingResearch.subject === '') {
            this.ruleForm.teachingResearch.subject = {
              cateId: '',
              itemName: '',
              itemCode: ''
            };
          }

          // 分类
          if (this.ruleForm.cateTags === '') {
            this.ruleForm.cateTags = [{
              tagList: []
            }];
          }
          // 获取选项
          this.getSelection();
        })
        .catch(error => {
          this.loading = false;
        });
    },

    // 获取选项
    async getSelection () {
      var teachingCode = this.ruleForm.teachingResearch.teachingTarget.itemCode;
      var phaseCode = this.ruleForm.teachingResearch.phase.itemCode;
      var subjectCode = this.ruleForm.teachingResearch.subject.itemCode;
      // 栏目分类参数
      var columnObj = {
        growthClassify: teachingCode || null,
        stageList: [phaseCode] || null,
        subjectList: [subjectCode] || null
      };
      // 查找栏目分类选项
      await findColumnTags({}).then(res => {
        this.options.cateTags = res.data;
        var cateTagsSelect = [];
        if (this.checkArr(this.ruleForm.cateTags)) {
          this.ruleForm.cateTags.map(item => {
            var items = this.options.cateTags.filter(data => data.tagsId === item.tagsId);
            if (items.length > 0) {
              cateTagsSelect.push(items[0].tagsId);
            }
          });
        }
        console.log('cateTagsSelect:', cateTagsSelect);
        this.ruleForm.cateTagsSelect = cateTagsSelect;
      });
      // // 分类标签参数
      var tagsObj = {
        growthClassify: teachingCode || null,
        stageId: phaseCode || null,
        subjectId: subjectCode || null,
        tagsKindEnum: 'TEACHINGRESEARCH',
        tagsTypeEnum: 'CATEGORY_TAGS'
      };
      // 查询分类标签选项
      await findTagsList({
        tagsKindEnum: 'TEACHINGRESEARCH',
        tagsTypeEnum: 'CATEGORY_TAGS'
      }).then(res => {
        this.options.colTags = res.data;
        var colTagsSelect = [];
        if (this.checkArr(this.ruleForm.colTags)) {
          this.ruleForm.colTags.map(item => {
            console.log('item:', item);
            var items = this.options.colTags.filter(data => data.tagsId === item.tagsId);
            if (items.length > 0) {
              colTagsSelect.push(items[0].tagsId);
            }
          });
        }
        console.log('colTagsSelect:', colTagsSelect);
        this.ruleForm.colTagsSelect = colTagsSelect;
      });
    },

    handleRemove (file, fileList) {
      console.log(file, fileList);
      this.ruleForm.fileList = fileList;
    },
    handlePreview (file) {
      console.log(file);
    },

    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    uploadSuccess (res, file) {
      console.log('上传成功:', URL.createObjectURL(file.raw));
      this.ruleForm.fileList.push({
        name: file.name,
        url: this.ruleForm.filesUrl
      });
    },
    beforeUpload (file) {
      // const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      // if (!imgStr.test(file.name)) {
      //   this.$message.error('上传格式不对，请重新上传!');
      //   return false;
      // }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        }).then(res => {
          console.log('文件上传：', res.data);
          this.action = res.data.action;
          this.uploadForm = res.data.parameters;
          this.ruleForm.filesUrl = res.data.uri;
          continueUpload = true;
          resolve(continueUpload);
        }).catch(err => {
          reject(continueUpload);
        });
      });
    },

    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('submit!');
          console.log('this.ruleForm.cateTagsSelect:', this.ruleForm.cateTagsSelect);

          // 分类
          if (this.ruleForm.cateTagsSelect.length > 0) {
            this.ruleForm.cateTags = [];
            this.ruleForm.cateTagsSelect.map(item => {
              var items = this.options.cateTags.filter(
                data => data.tagsId === item[0]
              );
              this.ruleForm.cateTags.push(items[0]);
            });
          }

          // 标签
          if (this.ruleForm.colTagsSelect.length > 0) {
            this.ruleForm.colTags = [];
            var arr = reduceArr(this.options.colTags);
            this.ruleForm.colTagsSelect.map(item => {
              var items = arr.filter(
                data => item[0] === data.tagsId
              );

              this.ruleForm.colTags.push(items[0]);
            });
          }

          console.log(this.ruleForm);
          updateReport(this.ruleForm).then(res => {
            console.log(res.data);
            this.$router.push({
              path: '/content/list',
              query: {
                tabsName: 'Report'
              }
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      //       var birthday = new Date("July 21, 1983 01:15:00")
      // document.write(birthday.getDate())
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.avatar-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  .icon-text {
    width: 200px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.step {
  span {
    margin: 0 8px;
  }
  .el-input {
    width: 90% !important;
  }
  .step-btn {
    margin-left: 20px;
    margin-top: 10px;
  }
}

.reportEditOrAdd {
  .content-box {
    padding: 40px;
    background: rgba(245, 246, 250, 1);
    .report-title {
      font-size: 20px;
      font-family: MicrosoftYaHei;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }

    .teaching-box {
      background-color: white;
      margin-top: 24px;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        margin-top: 40px;
        padding: 0 40px;
      }
      .textarea {
        height: 300px;
        padding: 20px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }
    }
    .button-box {
      margin-top: 24px;
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
